package com.huluobo.a2204parkdemo.notice

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.google.gson.Gson
import com.huluobo.base.bean.NewsBean
import com.huluobo.base.bean.NewsBeanItem
import com.huluobo.base.bean.NoticeBean
import com.huluobo.base.bean.NoticeBeanItem
import com.huluobo.base.net.ApiService
import com.huluobo.base.net.Const
import dagger.hilt.android.lifecycle.HiltViewModel
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception

/**
 *  Created by LC on 2024/8/28.
 */
class NoticePagingSource(val apiService: ApiService) : PagingSource<Int, NoticeBeanItem>() {
    var sum = 0
    override fun getRefreshKey(state: PagingState<Int, NoticeBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeBeanItem> {
        return try {
            val page = params.key ?: 0
            val map = mutableMapOf<String, Int>()
            map[Const.PARAM_PAGE] = page
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            val response = apiService.getAllNotice(body)
            val items = Gson().fromJson(response.values, NoticeBean::class.java)

            sum += items.size
            Log.i("TagA", "noticeItems:${sum}")

            val preKey = if (page > 0) page - 1 else null
            val nextKey = if (items.isNotEmpty()) page + 1 else null
            LoadResult.Page(items, preKey, nextKey)
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}